<template>
	<view class="appRecording">
		a
	</view>
</template>

<script>
	import encodeUtf8 from 'encode-utf8'
	export default {
		name: "appRecording",
		data() {
			return {
				recorder: '',
				voicePath: ''
			};
		},
		methods: {
			start() {
				if (!this.recorder) {
					console.log(123321)
					this.recorder = uni.getRecorderManager();
					this.recorder.onStop((res) => {
						console.log('recorder stop', res);
						this.voicePath = res.tempFilePath;
						this.getVoiceFile(res.tempFilePath)
					});
					this.recorder.onError(err => {
						console.log(err, '录音错误')
					})
					this.recorder.start()
				} else {
					this.recorder.start()
				}
			},
			stop() {
				console.log(222, 'stop')
				this.recorder.stop()
			},
			getVoiceFile(path) {
				console.log(path, 'path')
				try {
					plus.io.resolveLocalFileSystemURL(path, (entry) => {
						// 可通过entry对象操作test.html文件 
						console.log(entry, 'entry')
						entry.file((file) => {
							console.log(file,'file')
							// console.log(file.arrayBuffer(),'baset64')
							// return;
							var fileReader = new plus.io.FileReader();
							fileReader.readAsDataURL(file);
							fileReader.onloadend = (evt) => {
								const base64 = evt.target.result.split('base64,')[1]
								this.$request({
									url: '/api/v1/miletus/vip/speech/standardReco',
									method: 'post',
									data: {
										"engSerViceType": "8k_zh",
										"voiceFormat": "mp3",
										"sourceType": 1,
										data: base64
									}
								}).then(res => {
									if(!res.Result) {
										uni.showToast({
											title: '没听清您的讲话，请重试！',
											icon:'none'
										})
										this.$emit('fail')
									}else {
										this.$emit('success', res.Result)
									}
								})
							}
						});
					}, function(e) {
						console.log("Resolve file URL failed: " + e.message);
					});
				} catch (e) {
					//TODO handle the exception
					console.log(e, 'eee')
				}

			},
			utf8ToBase64(input) {
				var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
				var output = "";
				var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
				var i = 0;

				while (i < input.length) {

					chr1 = input.charCodeAt(i++);
					chr2 = input.charCodeAt(i++);
					chr3 = input.charCodeAt(i++);

					enc1 = chr1 >> 2;
					enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
					enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
					enc4 = chr3 & 63;

					if (isNaN(chr2)) {
						enc3 = enc4 = 64;
					} else if (isNaN(chr3)) {
						enc4 = 64;
					}

					output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);

				}

				return output;
			}
		}
	}
</script>

<style lang="scss">
	.appRecording {
		display: none;
	}
</style>